package com.ming.stringstudy.feedbacksystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ming.stringstudy.feedbacksystem.entity.Role;
import com.ming.stringstudy.feedbacksystem.mapper.RoleMapper;
import com.ming.stringstudy.feedbacksystem.mapper.RolePermissionMapper;
import com.ming.stringstudy.feedbacksystem.mapper.UserMapper;
import com.ming.stringstudy.feedbacksystem.pojo.PageBean;
import com.ming.stringstudy.feedbacksystem.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author aming
 * @since 2025-01-19
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageBean<Role> page(Integer page, Integer pageSize, Role role) {
        PageHelper.startPage(page, pageSize);

        List<Role> roleList = roleMapper.findByAttributes(role);

        PageInfo<Role> r = new PageInfo<>(roleList);
        PageBean pageBean = new PageBean(r.getTotal(), r.getList());
        return pageBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addRole(Role role) {
        if (roleMapper.findByRoleType(role.getRoleType()) != null) {
            return 0;
        }

        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());

        int result = roleMapper.insert(role);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(Role role) {
        if (roleMapper.findByRoleType(role.getRoleType()) != null) {
            return 0;
        }
        role.setUpdateTime(LocalDateTime.now());
        int result = roleMapper.updateById(role);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRole(List<Integer> ids) {
        int result = roleMapper.deleteBatchIds(ids);
        userMapper.updateUserByDeletedRoleId(ids);
        rolePermissionMapper.deleteRolePermissionByDeletedRoleId(ids);
        return result;
    }
}
